package com.application.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.platform.annotation.Table;
import com.platform.mvc.base.BaseModel;

import java.util.Date;

@SuppressWarnings("unused")
@Table(tableName = Message.table_name, pkName = "id")
public class Message extends BaseModel<Message> {


    public static final Message dao = new Message();

    public static final String table_name = "t_message";

    public static final String TYPE_SYS = "sys_msg";
    public static final String MODULE_ORDER = "order";
    public static final String MODULE_Charge = "vip_charge";
    public static final String MODULE_Withdraw = "withdraw";
    public static final String MODULE_Private = "private";

    public long getUnreadNum(int userid) {
        String s = "SELECT count(*) from t_message a where (type = ? or to_userid = ? )" +
                "and not exists ( select 1 from t_message_read b where b.userid = ? and b.message_id = a.id)";
        return Db.queryLong(s, TYPE_SYS, userid, userid);
    }

    public Page<Message> getPageData(int number, int size, int userIds) {
        String sel = "select a.*, b.read_time ";
        String from = "from t_message a left join t_message_read b on a.id = b.message_id and b.userid = ? " +
                " where type = ? or to_userid = ? order by a.id desc";

        Page<Message> page = Message.dao.paginate(number, size, sel, from, userIds, TYPE_SYS,userIds);

        page.getList().forEach(o -> {
            DictValue value = DictValue.dao.findByTypeAndCode(DictValue.type_message, o.getStr("type"));
            o.put("type_name", value == null ? "" : value.getValue());

            //设置消息已读
            boolean f = MessageRead.dao.isRead(userIds, o.getInt("id"));
            if(!f){
                MessageRead.dao.create(userIds, o.getInt("id"));
            }
        });

        return page;
    }

    //--------------web

    public boolean createNotice(String type, String title, String content, Integer fUserId, Integer toUserId,
                                String extra) {
        Message message = new Message();
        message.set("create_userid", fUserId == null ? 10000 : fUserId)
                .set("create_time", new Date())
                .set("title", title)
                .set("content", content)
                .set("to_userid", toUserId)
                .set("extra", extra)
                .set("type", type);
        return message.save();
    }

    public boolean createNotice(String type, String title, String content, Integer fUserId, Integer toUserId) {
        return createNotice(type, title, content, fUserId, toUserId, null);
    }
}
